package de.ars.client.items;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import de.ars.client.datahandling.DataMangementSystem;

import de.ars.client.datahandling.Person;
import de.ars.client.items.animators.SyncWithCsvAnimator;
import de.ars.client.items.elements.ListItem;
import de.ars.client.paintSystems.StringPainter;
import de.ars.client.screens.MainScreen;


public class SyncWithCsv  {
	
	private Vector personsTemp;
	private Vector personsStored;
	private MainScreen parent;
	
	public SyncWithCsv(MainScreen _parent)
	{
		this.parent = _parent;
		
    
        this.personsTemp = new Vector();
        this.personsStored = new Vector();
   	}	
	
	private Hashtable createHashTableFromVector(Vector _source)
	{
		Hashtable result = new Hashtable();
		Person currentPerson;
		String firstname;
		String lastname;
		
		Enumeration e = _source.elements();
        while( e.hasMoreElements())
        {
        	currentPerson = (Person)e.nextElement();
        	firstname = currentPerson.getInformation("person.firstname");
        	lastname = currentPerson.getInformation("person.lastname");
        	result.put(firstname+"_"+lastname, currentPerson);
        }
		return result;
	}
	
	public void syncPersonData(String csvFile)
	{
		// get loaded persons & persons from .csv
		this.personsTemp = DataMangementSystem.getPersonsToSync(csvFile);
		this.personsStored = this.parent.persons;
		Hashtable newPersons = createHashTableFromVector(personsTemp);
		Hashtable storedPersons = createHashTableFromVector(personsStored);
		
		Enumeration iterNewPersons = newPersons.keys();
		while(iterNewPersons.hasMoreElements())
		{
			String currentNewPersonName = (String)iterNewPersons.nextElement();
			if (storedPersons.containsKey(currentNewPersonName))
			{
				// update stored person
				Person currentStoredPerson = (Person)storedPersons.get(currentNewPersonName);
				Person currentNewPerson = (Person)newPersons.get(currentNewPersonName);
				Enumeration newPersonInfoIter = currentNewPerson.getInformationEnumeration();
				while (newPersonInfoIter.hasMoreElements())
				{
					String key = (String)newPersonInfoIter.nextElement();
					String value = currentNewPerson.getInformation(key);
					currentStoredPerson.putInformation(key, value);
				}
				
				// delete old person file
                DataMangementSystem.deleteFile(currentNewPersonName + ".txt");
                // save new person file
            	DataMangementSystem.saveNewPersonsToFS(currentNewPersonName + ".txt", currentStoredPerson);
            	
            	parent.getItem().updateItems();
			}
			else
			{
				// add new person
				parent.addPerson((Person)newPersons.get(currentNewPersonName));
			}
		}
	}
	
	public void sync(String _filename)
	{
		syncPersonData(_filename);		    			
	}	

}